#include "stdafx.h"

FileResizer::FileResizer(HWND parent, int width, int height)
	: FilerFrogElement(parent), m_width(width), m_height(height)
{
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
}
FileResizer::~FileResizer()
{
	GdiplusShutdown(gdiplusToken);
}

RESIZERERROR FileResizer::Resize(LPCWSTR sourceFilePath, int quality, const wstring& postfix, bool saveJPG, list<wstring>& newFiles, const wstring& wrapFolder )
{
	quality = quality*10;
	FileMachine fm(m_parent, sourceFilePath);

	Bitmap pBitmap(m_width, m_height);

	{
	Image myImage(sourceFilePath);
	Graphics graphics(&pBitmap);
	graphics.SetSmoothingMode(SmoothingModeHighQuality);
	graphics.SetInterpolationMode(InterpolationModeHighQualityBicubic);
	graphics.SetPixelOffsetMode(PixelOffsetModeHighQuality);
	RectF rect(0, 0, (REAL)m_width, (REAL)m_height);
	graphics.DrawImage(&myImage, rect, 0, 0, (REAL)myImage.GetWidth(), (REAL)myImage.GetHeight(), UnitPixel);
	}
	
	wstring mimetype;
	if (saveJPG)
	{
		mimetype = L"image/jpeg";
	}
	else
	{
		fm.MimeType(mimetype);
		if (mimetype == L"Undefined")
		{
			return RESIZERFAIL;
		}
	}

	CLSID clsid;
	FilesRefactorUtils::GetEncoderCLSID(mimetype.c_str(), &clsid);

	if (postfix == L"")
	{
		DeleteFileOperation dfo(m_parent, sourceFilePath, false, true, false);
		if (!dfo.Execute())
			wcout << "FAIL!" << endl;
	}

	wstring destFile;
	if (wrapFolder.c_str() == wstring(L""))
	{
		fm.AppendToFileNameWithPath(L"", postfix, destFile);
	}
	else
	{
		wstring target;
		fm.Folder(target);
		target += L"\\" + wrapFolder;
		if (!PathFileExists(target.c_str()))
		{
			CreateDirectory(target.c_str(), NULL);
		}
		fm.AppendToFileNameWithPath(wrapFolder.c_str() + wstring(L"\\"), L"", destFile);
	}
	if (saveJPG)
	{
		destFile = destFile.substr(0, destFile.find_last_of(L"."));
		destFile += L".jpg";
	}

	if (quality >= 0)
	{
		ULONG qua = quality;
		EncoderParameters param;
		param.Count                       = 1;
		param.Parameter[0].Guid           = EncoderQuality;
		param.Parameter[0].Type           = EncoderParameterValueTypeLong;
		param.Parameter[0].NumberOfValues = 1;
		param.Parameter[0].Value          = &qua;
		//param.Parameter[1].Guid			  = EncoderColorDepth;
		//param.Parameter[1].Type           = EncoderParameterValueTypeLong;
		//param.Parameter[1].NumberOfValues = 1;
		//ULONG depth = 24L;
		//param.Parameter[0].Value          = &depth;

		pBitmap.Save(destFile.c_str(), &clsid, &param);
	}
	else
	{
		pBitmap.Save(destFile.c_str(), &clsid, NULL);
	}
	
	if (wrapFolder.c_str() == wstring(L""))
	{
		newFiles.push_back(destFile);
	}

	return RESIZERSUCCESS;
}